<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>点对点聊天</title>
</head>

<body>




    <script>

        var websocket = null;

        // 判断当前浏览器是否支持websocket
        if(window.WebSocket) {

            websocket = new WebSocket("ws://127.0.0.1:8183/campus_runrun");
            //websocket = new WebSocket("wss://www.vtmer2018.top/wegdut");

            websocket.onopen = function() {
                var message = getMessage(0, 1, null  , null, null, null,null);
                websocket.send(JSON.stringify(message));
                console.log("建立连接.");
                // 定时发送心跳包
                setInterval("keepalive()", 10000);
                send();
            }
            websocket.onclose = function() {
                console.log("断开连接");
            }

            websocket.onmessage = function(e) {
                messageContent = e.data;
                console.log(messageContent);
            }

        }
        else {
            alert("当前浏览器不支持web socket");
        }


        function send() {
            // 构建对象
            var heartMessage = getMessage(1, 3, 6, "换行 <br>  第二行", 1, null);
            websocket.send(JSON.stringify(heartMessage));
        }


        // 不停地发送心跳包
        function keepalive () {
            // 构建对象
            var heartMessage = getMessage(2, 1, null, null, null, null);
            websocket.send(JSON.stringify(heartMessage));
        }


        function getMessage(type, fromUserId, toUserId, messageContent, messageType, ext) {
            return {
                type: type,
                chatRecordSendVO: {
                    fromUserId: fromUserId,
                    toUserId: toUserId,
                    messageContent: messageContent,
                    messageType: messageType
                },
                ext: ext
            };
        }




    </script>
</body>
</html>